import sys
import ctypes
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QStackedWidget, QLabel, QProgressBar, QTableWidgetItem, QTableWidget, QHeaderView
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput
from PySide6.QtMultimediaWidgets import QVideoWidget
from PySide6.QtCore import QUrl, QTimer, QEvent, Qt
from PySide6.QtGui import QIcon, QFont, QPainter
from PySide6.QtCharts import QChartView, QChart, QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis

# 设置 AppUserModelID
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("myappid")

# 假设资源路径函数，用于获取图片资源路径


def get_resource_path(relative_path):
    return relative_path  # 根据实际情况调整


class VideoPlayer(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()
        self.setLayout(layout)

        # 视频播放组件
        self.video_widget = QVideoWidget()
        layout.addWidget(self.video_widget)

        # 初始化视频播放器
        self.media_player = QMediaPlayer(self)
        self.audio_output = QAudioOutput(self)
        self.media_player.setAudioOutput(self.audio_output)
        self.media_player.setVideoOutput(self.video_widget)
        video_path = QUrl.fromLocalFile(
            R"C:\Users\apple tree\Videos\屏幕录制\屏幕录制 2024-08-19 134436.mp4")
        self.media_player.setSource(video_path)

        # 播放视频
        self.media_player.play()

    # 切换播放和暂停
    def toggle_play_pause(self):
        # 仅当满载警告未显示时才允许播放
        if self.parent().full_alert_displayed:
            return  # 满载状态下不播放视频
        if self.media_player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
            self.media_player.pause()
        else:
            self.media_player.play()

    # 暂停视频
    def pause_video(self):
        if self.media_player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
            self.media_player.pause()

    # 继续播放视频
    def resume_video(self):
        if self.media_player.playbackState() != QMediaPlayer.PlaybackState.PlayingState:
            self.media_player.play()


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("智能垃圾桶系统")
        self.showFullScreen()
        # self.resize(800, 600)

        # 设置窗口图标
        self.setWindowIcon(QIcon(get_resource_path("img/garbageicon.png")))

        # 设置背景颜色为白色
        self.setStyleSheet("background-color: white;")

        # 初始化垃圾数量统计
        self.garbage_counts = [0, 0, 0, 0]  # 可回收垃圾、有害垃圾、厨余垃圾、其他垃圾
        self.entry_number = 1  # 记录序号

        # 每页显示行数
        self.items_per_page = 10  # 每页显示10条信息
        self.current_page = 1
        self.total_entries = []  # 储存所有垃圾信息

        # 创建堆叠布局和主界面布局
        self.stacked_widget = QStackedWidget()
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        # 创建切换按钮，设置按钮颜色为绿色，字体为20px
        self.home_button = QPushButton("首页")
        self.home_button.setStyleSheet(
            "background-color: green; color: white; padding: 10px;")
        self.home_button.setFont(QFont("Arial", 20))  # 设置字体大小为20px

        self.stats_button = QPushButton("垃圾统计")
        self.stats_button.setStyleSheet(
            "background-color: green; color: white; padding: 10px;")
        self.stats_button.setFont(QFont("Arial", 20))  # 设置字体大小为20px

        self.info_button = QPushButton("已分类垃圾信息")
        self.info_button.setStyleSheet(
            "background-color: green; color: white; padding: 10px;")
        self.info_button.setFont(QFont("Arial", 20))  # 设置字体大小为20px

        # 按钮布局
        button_layout = QHBoxLayout()
        button_layout.addWidget(self.home_button)
        button_layout.addWidget(self.stats_button)
        button_layout.addWidget(self.info_button)

        # 创建页面
        self.home_page = VideoPlayer()  # 视频播放界面
        self.stats_page = self.create_stats_page()  # 垃圾统计界面
        self.info_page = self.create_info_page()  # 已分类垃圾信息界面

        # 添加页面到堆栈
        self.stacked_widget.addWidget(self.home_page)
        self.stacked_widget.addWidget(self.stats_page)
        self.stacked_widget.addWidget(self.info_page)

        # 将控件添加到主布局
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.stacked_widget)

        # 绑定按钮到相应的界面
        self.home_button.clicked.connect(
            lambda: self.switch_to_page(self.home_page))
        self.stats_button.clicked.connect(
            lambda: self.switch_to_page(self.stats_page))
        self.info_button.clicked.connect(
            lambda: self.switch_to_page(self.info_page))

        # 默认显示首页
        self.stacked_widget.setCurrentWidget(self.home_page)

        # 添加无操作计时器
        self.inactivity_timer = QTimer(self)
        self.inactivity_timer.setInterval(2000)  # 2秒
        self.inactivity_timer.timeout.connect(self.switch_to_home)

        # 追踪用户操作，安装事件过滤器
        self.installEventFilter(self)

        # 满载警告标志和显示
        self.full_alert_displayed = False
        self.create_full_alert()
        # self.info_page = self.create_info_page()  # 创建垃圾信息展示页

    def create_full_alert(self):
        self.full_alert = QLabel("垃圾桶已满，请更换！按键 5 以继续")
        self.full_alert.setStyleSheet(
            "background-color: red; color: white; font-size: 32px;")
        self.full_alert.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.full_alert.setVisible(False)
        self.layout().addWidget(self.full_alert)

    def switch_to_page(self, page):
        if not self.full_alert_displayed:
            if page == self.home_page:
                self.home_page.resume_video()
            else:
                self.home_page.pause_video()
            self.stacked_widget.setCurrentWidget(page)
            self.inactivity_timer.start()  # 无操作计时器重置

    def switch_to_home(self):
        self.stacked_widget.setCurrentWidget(self.home_page)
        self.home_page.resume_video()
        self.inactivity_timer.stop()

    def create_stats_page(self):
        page = QWidget()
        layout = QVBoxLayout()
        page.setLayout(layout)

        # 上半部分：显示四个垃圾桶的满载率
        self.progress_bars = []
        garbage_types = ["可回收垃圾", "有害垃圾", "厨余垃圾", "其他垃圾"]
        for i, type_name in enumerate(garbage_types):
            bar = QProgressBar()
            bar.setRange(0, 10)  # 假设10为满载
            bar.setValue(self.garbage_counts[i])
            bar.setFormat(f"{type_name} 满载率: %p%")
            layout.addWidget(bar)
            self.progress_bars.append(bar)

        # 下半部分：显示垃圾数量统计
        self.chart_view = self.create_chart_view()
        layout.addWidget(self.chart_view)

        return page

    def update_stats_display(self):
        # 更新进度条
        for i, bar in enumerate(self.progress_bars):
            bar.setValue(self.garbage_counts[i])

        # 更新图表数据
        self.chart_view.setChart(self.create_chart())

    def check_full_capacity(self, category):
        if self.garbage_counts[category - 1] >= 10:
            self.show_full_alert()

    def show_full_alert(self):
        self.full_alert.setVisible(True)
        self.full_alert_displayed = True
        self.stacked_widget.setCurrentWidget(self.home_page)

    def hide_full_alert(self):
        self.full_alert.setVisible(False)
        self.full_alert_displayed = False
        self.home_page.resume_video()

    def create_chart_view(self):
        chart_view = QChartView(self.create_chart())
        chart_view.setRenderHint(QPainter.RenderHint.Antialiasing)
        chart_view.setMinimumSize(800, 400)
        return chart_view

    def create_chart(self):
        chart = QChart()
        chart.setTitle("垃圾数量统计")

        series = QBarSeries()
        set0 = QBarSet("垃圾数量")
        set0.append(self.garbage_counts)
        series.append(set0)
        chart.addSeries(series)

        categories = ["可回收", "有害", "厨余", "其他"]
        axisX = QBarCategoryAxis()
        axisX.append(categories)
        chart.addAxis(axisX, Qt.AlignmentFlag.AlignBottom)
        series.attachAxis(axisX)

        axisY = QValueAxis()
        axisY.setRange(0, max(10, max(self.garbage_counts)))
        chart.addAxis(axisY, Qt.AlignmentFlag.AlignLeft)
        series.attachAxis(axisY)

        return chart

    # 表格展示设计
    def create_info_page(self):
        # 垃圾信息页面
        page = QWidget()
        layout = QVBoxLayout(page)

        # 表格设置
        self.table_widget = QTableWidget()
        self.table_widget.setColumnCount(3)
        self.table_widget.setHorizontalHeaderLabels(["序号", "垃圾类别", "数量"])
        self.table_widget.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeMode.Stretch)

        # 美化表格
        self.table_widget.setStyleSheet("""
            QTableWidget {
                font-size: 18px;
                background-color: #f0f8ff;  /* 浅蓝色背景 */
                border: 1px solid #b0c4de;  /* 边框颜色 */
            }
            QHeaderView::section {
                background-color: #4682b4;  /* 标题栏背景色 */
                color: white;
                font-size: 20px;
                padding: 6px;
                border: 1px solid #b0c4de;
            }
            QTableWidget::item {
                padding: 10px;
                color: #000080;  /* 文字颜色 */
            }
            QTableWidget::item:selected {
                background-color: #87cefa;  /* 选中行的背景颜色 */
                color: #000000;
            }
        """)

        # 页码控制
        pagination_layout = QHBoxLayout()
        self.previous_button = QPushButton("上一页")
        self.next_button = QPushButton("下一页")
        self.page_label = QLabel("第 1 页")

        # 美化分页按钮
        self.previous_button.setStyleSheet("""
            font-size: 16px; 
            padding: 6px;
            background-color: #3cb371;  /* 深绿色 */
            color: white;
            border-radius: 4px;
        """)
        self.next_button.setStyleSheet("""
            font-size: 16px; 
            padding: 6px;
            background-color: #3cb371;  /* 深绿色 */
            color: white;
            border-radius: 4px;
        """)
        self.page_label.setStyleSheet(
            "font-size: 16px; color: #333333;")  # 美化页码标签

        pagination_layout.addWidget(self.previous_button)
        pagination_layout.addWidget(
            self.page_label, alignment=Qt.AlignmentFlag.AlignCenter)
        pagination_layout.addWidget(self.next_button)

        # 加入到布局
        layout.addWidget(self.table_widget)
        layout.addLayout(pagination_layout)

        # 分页信号槽连接
        self.previous_button.clicked.connect(self.load_previous_page)
        self.next_button.clicked.connect(self.load_next_page)
        self.current_page = 1
        self.items_per_page = 10
        self.displayed_data = []

        return page

    def update_info_display(self, category):
        # 更新表格数据
        garbage_types = ["可回收垃圾", "有害垃圾", "厨余垃圾", "其他垃圾"]
        self.garbage_counts[category - 1] += 1
        row_data = [str(self.entry_number), garbage_types[category - 1],
                    str(self.garbage_counts[category - 1])]
        self.displayed_data.append(row_data)
        self.entry_number += 1

        # 计算当前显示页，若超过当前页容量自动跳转至下一页
        self.current_page = (len(self.displayed_data) -
                             1) // self.items_per_page + 1
        self.load_table_page(self.current_page)

        # 切换到信息展示页
        self.switch_to_page(self.info_page)
        self.update_stats_display()
        self.check_full_capacity(category)

    def load_table_page(self, page_number):
        # 加载指定页的数据
        self.table_widget.setRowCount(0)
        start_index = (page_number - 1) * self.items_per_page
        end_index = min(start_index + self.items_per_page,
                        len(self.displayed_data))
        for row_data in self.displayed_data[start_index:end_index]:
            row_index = self.table_widget.rowCount()
            self.table_widget.insertRow(row_index)
            for col_index, data in enumerate(row_data):
                self.table_widget.setItem(
                    row_index, col_index, QTableWidgetItem(data))
        self.page_label.setText(f"第 {page_number} 页")

    def load_previous_page(self):
        # 加载上一页，并确保在垃圾信息界面
        if self.current_page > 1:
            self.current_page -= 1
            self.load_table_page(self.current_page)
        self.switch_to_page(self.info_page)  # 保持在信息展示页
        self.inactivity_timer.start()

    def load_next_page(self):
        # 加载下一页，并确保在垃圾信息界面
        if (self.current_page * self.items_per_page) < len(self.displayed_data):
            self.current_page += 1
            self.load_table_page(self.current_page)
        self.switch_to_page(self.info_page)  # 保持在信息展示页
        self.inactivity_timer.start()

    def eventFilter(self, obj, event):
        if event.type() == QEvent.Type.KeyPress:
            key = event.key()
            if key in [Qt.Key.Key_1, Qt.Key.Key_2, Qt.Key.Key_3, Qt.Key.Key_4]:
                if not self.full_alert_displayed:
                    category = key - Qt.Key.Key_1 + 1
                    self.update_info_display(category)
                    self.inactivity_timer.start()
                return True
            elif key == Qt.Key.Key_5 and self.full_alert_displayed:
                self.reset_full_bins()
                return True
            elif key == Qt.Key.Key_6:
                self.resize(800, 600)
                return True

        elif event.type() in [QEvent.Type.MouseButtonPress, QEvent.Type.KeyPress]:
            self.inactivity_timer.start()
        return super().eventFilter(obj, event)

    def reset_full_bins(self):
        for i in range(len(self.garbage_counts)):
            if self.garbage_counts[i] >= 10:
                self.garbage_counts[i] = 0
        self.update_stats_display()
        self.hide_full_alert()
        # 恢复视频播放
        self.full_alert_displayed = False  # 重置状态
        self.home_page.resume_video()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec())
